package com.android.thought.badboys.Call;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.provider.CallLog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.android.thought.badboys.BadBoysApplication;
import com.android.thought.badboys.Model;
import com.android.thought.badboys.R;
import com.android.thought.badboys.Action.IBackupAccessAction;
import com.android.thought.badboys.Info.CallInfo;
import com.android.thought.badboys.Info.DataConversion;
import com.android.thought.badboys.Info.ListBackup;

public class CallActivity extends Activity implements View.OnClickListener /*, ICallAction*/ {

	
	Button mBtn_Call_All = null;
	Button mBtn_Call_Miss = null;
	Button mBtn_Call_In = null;
	Button mBtn_Call_Out = null;
	
	View mSelectView = null;
	
	ListView mListView_Call;
	CallAdapter mAdapter_Call;
	
	Model mModel = null;
	int mLoadType = 0;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.call_layer);

		this.mBtn_Call_All = (Button) this.findViewById(R.id.btn_call_all);
		this.mBtn_Call_In = (Button) this.findViewById(R.id.btn_call_in);
		this.mBtn_Call_Out = (Button) this.findViewById(R.id.btn_call_out);
		this.mBtn_Call_Miss = (Button) this.findViewById(R.id.btn_call_miss);
		
		this.mBtn_Call_All.setOnClickListener(this);
		this.mBtn_Call_In.setOnClickListener(this);
		this.mBtn_Call_Out.setOnClickListener(this);
		this.mBtn_Call_Miss.setOnClickListener(this);

		this.mListView_Call = (ListView) this.findViewById(R.id.listview_call);
	
		mSelectView = this.mBtn_Call_All;
		mSelectView.setSelected(true);
		
		onLoadData(0);
	}
	
	void onLoadData(final int type) {
		
		if ( mModel == null ) {
			Application app = getApplication();
		
			if ( app instanceof BadBoysApplication ) {
				mModel = ((BadBoysApplication)app).getModel();
			}
		}
		
		if ( mModel != null ) {
			
			
			this.mModel.getBackUpInfo(this, new IBackupAccessAction() {
				
				@Override
				public void onSaveComplated(boolean isSucess) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onLoadComplated(ListBackup backup) {
					
					
					final int in = backup.getData().size();

					if ( in > 0 )
					if (mListView_Call != null) {
						
						ArrayList<DataConversion> conver = backup.getData();
						
						final ArrayList<CallInfo> call = new ArrayList<CallInfo>();
						
						if( type == 0 ) { 
							for ( int index = conver.size()-1; index > -1; index--) {
								DataConversion data = conver.get(index);
								
								
								ArrayList<CallInfo> allCallInfos = data.getCallGroupInfo();
								
								call.addAll(allCallInfos);
							}
						} else{
							for ( DataConversion data : conver ) {
								
								ArrayList<CallInfo> allCallInfos = data.getCallGroupInfo();
								
								for (CallInfo callInfo : allCallInfos) {
									if ( type == CallLog.Calls.MISSED_TYPE ) {
										if ( callInfo.getType() != CallLog.Calls.INCOMING_TYPE && callInfo.getType() != CallLog.Calls.OUTGOING_TYPE )
											call.add(callInfo);
									} else {
										if ( callInfo.getType() == type ) 
										call.add(callInfo);
									}
								}
							}
						}

						Collections.sort(call, new CallInfo());
						
						if (mAdapter_Call == null) {
							mAdapter_Call = new CallAdapter(CallActivity.this, call);
							mListView_Call.setAdapter(mAdapter_Call);
						} else {
							mAdapter_Call.notifyDataSetChanged(call);
						}
					}
				}
			}, true);
		}
	}

	@Override
	public void onClick(View v) {
		final int id = v.getId();
		
		if( mSelectView != null )
			mSelectView.setSelected(false);
		
		if (id == R.id.btn_call_all) {
			onLoadData(0);
		} else if (id == R.id.btn_call_miss) {
			onLoadData(CallLog.Calls.MISSED_TYPE);
		} else if ( id == R.id.btn_call_in) {
			onLoadData(CallLog.Calls.INCOMING_TYPE);
		}  else if ( id == R.id.btn_call_out) { 
			onLoadData(CallLog.Calls.OUTGOING_TYPE);
		}
		
		mSelectView = v;
		mSelectView.setSelected(true);
	}	

	public class CallAdapter extends BaseAdapter implements OnClickListener {
		private Context mContext;
		ArrayList<CallInfo> mList = null;

		SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy - MM - dd   HH : mm "/* : ss" */);
		Calendar mCalendar;

		public CallAdapter(Context context, List<CallInfo> list) {
			mContext = context;
			mList = (ArrayList<CallInfo>) list;

			mCalendar = Calendar.getInstance();
		}

		public int getCount() {
			return mList.size();
		}

		public CallInfo getItem(int position) {
			return mList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		@Override
		public void notifyDataSetChanged() {

			super.notifyDataSetChanged();
		}

		public void notifyDataSetChanged(ArrayList<CallInfo> list) {

			mList = list;
			super.notifyDataSetChanged();
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			Warrper warrper ;
			if (convertView == null) {
				view = LayoutInflater.from(mContext).inflate(R.layout.call_row, null);
			} else {
				view = (View) convertView;
			}

			Object obj = view.getTag();
			
			if ( obj == null || ! (obj instanceof Warrper) ) {
				warrper = new Warrper(view);
				view.setTag(warrper);
			} else { 
				warrper = (Warrper) obj;
			}
			

			final TextView textview_name = warrper.getTextview_Name();
			final TextView textview_date = warrper.getTextview_Date();
			final View pView = warrper.getPView();

			final CallInfo info = getItem(position);

			final String name = info.getName();
			final String number = info.getNumber();
			
			int bgReg = R.drawable.selector_btn_defult; // 부재중
			
			if (info.getType() == CallLog.Calls.OUTGOING_TYPE )
				bgReg = R.drawable.selector_btn_out_bg;
			else if ( info.getType() == CallLog.Calls.INCOMING_TYPE )
				bgReg = R.drawable.selector_btn_in_bg;
			
			view.setBackgroundResource(bgReg);

			String value = name;

			if (value == null || value.length() <= 0)
				value = number;

			mCalendar.setTimeInMillis(info.getTime());
			
			textview_name.setText(value);
			textview_date.setText(mDateFormat.format(mCalendar.getTime()));

			pView.setTag(R.id.ids_item_tag, info);
			pView.setOnClickListener(this);

			return view;
		}

		@Override
		public void onClick(View v) {
			Object obj = v.getTag(R.id.ids_item_tag);

		}
	}
	
	class Warrper {
		View mPview = null;
		TextView mTextview_name= null;
		TextView mTextview_date = null;
		
		public Warrper(View view) {
			this.mPview = view.findViewById(R.id.linear_call_row_p);
			this.mTextview_date= (TextView) view.findViewById(R.id.textview_call_date);
			this.mTextview_name= (TextView) view.findViewById(R.id.textview_call_name);
		}
		
		public View getPView(){
			return this.mPview;
		}
		
		public TextView getTextview_Name() { 
			return this.mTextview_name;
		}
		public TextView getTextview_Date() { 
			return this.mTextview_date;
		}
	}
	
}

/*
	class CallTask extends AsyncTask<ICallAction, Void, List<CallInfo>> {

		// CallLog.Calls.OUTGOING_TYPE ( 발신)
		// CallLog.Calls.INCOMING_TYPE ( 수신)
		// CallLog.Calls.MISSED_TYPE ( 부재중)

		ICallAction mListener;

		ProgressDialog mProgressDialog;
		Context mContext;
		int mType = -1;

		public CallTask(Context context, int Type) {
			mContext = context;
			mType = Type;
		}

		@Override
		protected List<CallInfo> doInBackground(ICallAction... params) {

			if (params != null && params.length > 0) {
				mListener = params[0];
				return onLoadData();
			}

			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Log.e("CH_DBUG", "########## onPostExecute");
			this.mProgressDialog = new ProgressDialog(mContext);
			this.mProgressDialog.setMessage("잠시만 기다려 주세요. \n통화기록을 로딩중입니다.");
			this.mProgressDialog.setCancelable(true);
			this.mProgressDialog.show();

			this.mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					onCancelled();
				}
			});

		}

		@Override
		protected void onCancelled() {
			
			super.onCancelled();
			Log.e("CH_DBUG", "########## CANCEL");
			if ( mListener != null ) 
				mListener.onLoadComplated(null);
		}

		@Override
		protected void onPostExecute(List<CallInfo> result) {
			Log.e("CH_DBUG", "########## onPostExecute");
			
			super.onPostExecute(result);

			if (this.mProgressDialog != null)
				this.mProgressDialog.dismiss();

			this.mProgressDialog = null;
			this.mContext = null;

			if (this.mListener != null)
				this.mListener.onLoadComplated(result);
		}

		private ArrayList<CallInfo> onLoadData() {
			Cursor cursor = null;

			if (mType == CallLog.Calls.OUTGOING_TYPE || mType == CallLog.Calls.INCOMING_TYPE
					|| mType == CallLog.Calls.MISSED_TYPE) {
				cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.TYPE + "= ?",
						new String[] { String.valueOf(CallLog.Calls.OUTGOING_TYPE) }, CallLog.Calls.DEFAULT_SORT_ORDER);
			} else { 
				cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null , null , CallLog.Calls.DEFAULT_SORT_ORDER);
			}

			ArrayList<CallInfo> arrayInfo = new ArrayList<CallInfo>();

			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				while (cursor.isAfterLast() == false) {

					CallInfo info = new CallInfo();
					info.setType(cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE)));
					info.setName(cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
					info.setNumber(cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)));
					info.setDuration(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION)));
					info.setTime(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)));

					arrayInfo.add(info);
					
					cursor.moveToNext();
					
				}
			}

			if (cursor != null)
				cursor.close();

			return arrayInfo;
		}
	}*/